/**
 * Created by Tuffy on 16/1/18.
 */
'use strict';

angular.module('starter.controllers')

.controller('HotelBaseInfoEditCtrl', ['$scope','$rootScope', '$state', '$ionicBackdrop', 'HotelService','$cordovaToast','$ionicLoading', 'Settings', 'QiniuUploadToken','$filter',
    function($scope, $rootScope, $ionicBackdrop, $state, HotelService, $cordovaToast,$ionicLoading, Settings, QiniuUploadToken,$filter) {
    var type = 'HotelBaseInfo',
        format = function(_data){
            var date = new Date(),
                openDate = new Date();
            if(_data.decorateTime)
                date.setTime(_data.decorateTime);
            _data.decorateDate = date;

            if(_data.openTime)
                openDate.setTime(_data.openTime);
            _data.openDate = openDate;
            _data.retention_time = Tools.timeStr2FormatTime(_data.retentionTime);
            _data.default_leave_time = Tools.timeStr2FormatTime(_data.defaultLeaveTime);
        },
        getSaveData = function(data){
            var keys = ['def','lobby','mainHousing'],
                pics = [];
            for(var i in keys){
                var key = keys[i];
                pics.push({
                    name:key,
                    pic: data[key] ? data[key] : []
                });
            }
            data.pics = JSON.stringify(pics);
            data.decorateTime = data.decorateDate.getTime();
            data.openTime = data.openDate.getTime();
            return {
                hotelId:$rootScope.EDIT_HOTEL.id,
                hotelName:data.hotelName,
                hotelPhone:data.hotelPhone,
                defaultLeaveTime: $scope.hotel.default_leave_time.Format('HHmmss'),
                retentionTime: $scope.hotel.retention_time.Format('HHmmss'),
                introduction: $scope.hotel.introduction,
                decorateTimeStr:$filter('date')(data.decorateDate,'yyyy-MM-dd'),
                openTimeStr:$filter('date')(data.openDate,'yyyy-MM-dd'),
                businessLicenseFront: $scope.hotel.businessLicenseFront,
                idCardFront: $scope.hotel.idCardFront,
                idCardBack: $scope.hotel.idCardBack,
                remark: $scope.hotel.remark,
                pics: data.pics
            };
        };
    $scope.hotel = $rootScope.EDIT_DATE[type] ? $rootScope.EDIT_DATE[type] : {};


    $scope.doSave = function(){
        $ionicLoading.show({
            template: '保存中...'
        });
        HotelService.setHotelBasicInfo(getSaveData($scope.hotel))
            .success(function(res){
                if(res.success){
                    var rntData = {};
                    rntData[type] = $scope.hotel;
                    $rootScope.$broadcast('EDIT_COMPLETE',rntData);
                    $scope.$ionicGoBack();
                }else{
                    $cordovaToast.showShortBottom(res.errorMsg || '保存失败');
                }
            })
            .error(function(){
        
            })
            .finally(function(){
                $ionicLoading.hide();
            });
    };

    // 显示画廊
    $scope.showGallery = function(type, photoNum, key) {
        var photosList = [];
        var types = 'def, lobby, mainHousing';
        if (type) {
            angular.forEach($scope.hotel[type], function(item) {
                photosList.push({
                    src: item.url,
                    sub: ''
                });
            });
        }
        if (type && types.indexOf(type) < 0) {
            photosList.push({
                src: type,
                sub: ''
            });
        }
        ImageGallery.show($rootScope, '酒店信息', photosList, QiniuUploadToken, photoNum,function(result){
            var urls = [];
            for(var i in result){
                var item = result[i];
                urls.push({
                    url: item
                });
            }
            if(key) {
                if (urls.length > 0) {
                    $scope.hotel[key] = urls[0].url;
                } else {
                    $scope.hotel[key] = '';
                }
            } else {
                $scope.hotel[type] = urls;
            }
        });
    };

    format($scope.hotel);

}])
.controller('HotelLocationEditCtrl', ['$scope','$rootScope', '$state','LocationService','$cordovaToast','$ionicLoading',
    function($scope,$rootScope, $state,LocationService,$cordovaToast,$ionicLoading) {
    var type = 'HotelLocationEdit',
        format = function(_data){
            _data.provinceCode = parseInt(_data.provinceCode);
            _data.cityCode = parseInt(_data.cityCode);
            _data.districtCode = parseInt(_data.districtCode);
            return _data;
        },
        init = function(){
            provinces();
        },
        provinces = function(){
            $ionicLoading.show({
                template: '<ion-spinner icon="ios"></ion-spinner>'
            });
            LocationService.provinces()
                .success(function(res){
                    if(res && res.length>0){
                        $scope.DICT['province'] = res;
                    }
                })
                .error(function(err){
                    console.log(err);
                })
                .finally(function(){
                    $ionicLoading.hide();
                });
        },
        cities = function(proId){
            $ionicLoading.show({
                template: '<ion-spinner icon="ios"></ion-spinner>'
            });
            LocationService.cities(proId)
                .success(function(res){
                    if(res && res.length>0){
                        $scope.DICT['city'] = res;
                    }
                })
                .error(function(err){
                    console.log(err);
                })
                .finally(function(){
                    $ionicLoading.hide();
                });
        },
        districts = function(cityId){
            $ionicLoading.show({
                template: '<ion-spinner icon="ios"></ion-spinner>'
            });
            LocationService.districts(cityId)
                .success(function(res){
                    if(res && res.length>0){
                        $scope.DICT['district'] = res;
                    }
                })
                .error(function(err){
                    console.log(err);
                })
                .finally(function(){
                    $ionicLoading.hide();
                });
        };
    $scope.hotel = $rootScope.EDIT_DATE[type] ? format($rootScope.EDIT_DATE[type]) : {};
    $scope.DICT = {
        province:[],
        city:[],
        district:[]
    };
    /**
     * 监听省变化
     */
    $scope.$watch('hotel.provinceCode',function(newVal){
        if(newVal && newVal!=null)
            cities(newVal);
        else{
            $scope.DICT['city'] = [];
        }
    });
    /**
     * 监听市变化
     */
    $scope.$watch('hotel.cityCode',function(newVal){
        if(newVal && newVal!=null)
            districts(newVal);
        else{
            $scope.DICT['district'] = [];
        }
    });
    $scope.doSave = function(){
        $ionicLoading.show({
            template: '保存中...'
        });
        LocationService.setProvAndCityAndArea($scope.hotel)
            .success(function(res){
                if(res.success){
                    var rntData = {};
                    //$scope.hotel['province'] = _.findWhere($scope.DICT['province'],{'proId': $scope.hotel['provinceCode']});
                    rntData[type] = $scope.hotel;
                    $rootScope.$broadcast('EDIT_COMPLETE',rntData);
                    $scope.$ionicGoBack();
                }else{
                    $cordovaToast.showShortBottom('保存失败');
                }
            })
            .error(function(){

            })
            .finally(function(){
                $ionicLoading.hide();
            });
    };
    init();
}])
.controller('HotelRoomInfoEditCtrl', ['$scope','$rootScope', '$state','HotelService','$cordovaToast','$ionicLoading','QiniuUploadToken',
    function($scope,$rootScope, $state,HotelService,$cordovaToast,$ionicLoading,QiniuUploadToken) {
    var type = 'HotelRoomInfoEdit',
        getSaveData = function(data){
            var keys = ['def','toilet','bed'],
                pics = [],
                bedSize = [];
            for(var i in keys){
                var key = keys[i];
                pics.push({
                    name:key,
                    pic: data[key] ? data[key] : []
                });
            }
            for(var i in data.bedSize){
                var item = data.bedSize[i];
                if(item.length>0){
                    bedSize.push(item);
                }
            }
            data.pics = JSON.stringify(pics);
            return {
                roomTypeId:data.roomTypeId,
                area:data.area,
                washroom:data.washroom,
                bedType:data.bedType,
                pics:data.pics,
                bedSize:bedSize.join(',')
            };
        };

    $scope.hotelRoomInfo = $rootScope.EDIT_DATE[type] ? $rootScope.EDIT_DATE[type] : {};
    $scope.DICT = {
        washroom:[{
            id:'22',
            name:'公共卫浴'
        },{
            id:'17',
            name:'独立卫浴'
        }],
        bedTypes : [
            {id:'1',name:"单床房",bedCount:1},
            {id:'2',name:"双床房",bedCount:2},
            {id:'3',name:"其它",bedCount:3}
        ],
        sizeTypes: [
            {id:'2.20',name:"2.20m"},
            {id:'2.00',name:"2.00m"},
            {id:'1.80',name:"1.80m"},
            {id:'1.50',name:"1.50m"},
            {id:'1.35',name:"1.35m"},
            {id:'1.20',name:"1.20m"},
            {id:'1.00',name:"1.00m"}
        ]
    };
    $scope.$watch('hotelRoomInfo.bedType',function(newVal){
        if(newVal){
           $scope.hotelRoomInfo.bedSize = [];
            for(var i=0;i<parseInt(newVal);i++){
                $scope.hotelRoomInfo.bedSize.push('');
            }
        }
    });
    // 显示画廊
    $scope.showGallery = function(type,photoNum) {
        var photosList = [];
        angular.forEach($scope.hotelRoomInfo[type], function(item) {
            photosList.push({
                src: item.url,
                sub: ''
            });
        });
        ImageGallery.show($rootScope, '房型信息', photosList, QiniuUploadToken, photoNum,function(result){
            var urls = [];
            for(var i in result){
                var item = result[i];
                urls.push({
                    url:item
                });
            }
            $scope.hotelRoomInfo[type] = urls;
        });
    };
    $scope.doSave = function(){
        $ionicLoading.show({
            template: '保存中...'
        });
        HotelService.setRoomTypeInfo(getSaveData($scope.hotelRoomInfo))
            .success(function(res){
                if(res.success){
                    var rntData = {};
                    rntData[type] = $scope.hotelRoomInfo;
                    $rootScope.$broadcast('EDIT_COMPLETE',rntData);
                    $scope.$ionicGoBack();
                }else{
                    $cordovaToast.showShortBottom('保存失败');
                }
            })
            .error(function(){

            })
            .finally(function(){
                $ionicLoading.hide();
            });
    };

}])
.controller('HotelVisitEditCtrl', ['$scope','$rootScope', '$filter','VisitService','HotelService','$cordovaToast','$ionicLoading','$ionicModal',
    function($scope,$rootScope, $filter,VisitService,HotelService,$cordovaToast,$ionicLoading,$ionicModal) {
        var type = 'HotelVisitEdit',
            roleDict = {
                1:'老板',
                2:'前台'
            },
            init = function(){
                findContacts();
                //设置字典
                for(var key in $scope.dict){
                    findDict(key);
                }

                $scope.dict['purchase_intention'] = {
                    'T':'是',
                    'F':'否'
                };
            },format = function(data){
                data.visitDate = data.visitTime ? new Date(data.visitTime) : new Date();
                data.hotelName = $rootScope.EDIT_HOTEL.hotelName;
                data.visitHotelId = $rootScope.EDIT_HOTEL.id;
                return data;
            },
            formatSave = function(data){
                data.visitTime = $filter('date')(data.visitDate,'yyyyMMddHHmmss');
                if(data.reason){
                    data.visitFailReason = JSON.stringify(data.reason);
                    delete data.reason;
                }
                if(!data.id){
                    delete data.id;
                }
                delete data.visitDate;
                return data;
            },
            formatContact = function(data){
                $scope.hotelContacts = [];
                for(var i in data){
                    var contact = data[i],
                        name=contact.name?contact.name:'',
                        role=roleDict[contact.roleId];
                    $scope.hotelContacts.push({
                        id:name,
                        name:name + '  '+role
                    });
                    // if(!$scope.visit.hotelContacts){ //默认值
                    //     $scope.visit.hotelContacts = name;
                    // }
                }
            },findDict = function(dictName,okFunc){
                VisitService.findDict(dictName)
                    .success(function(res){
                        if(res.success){
                            $scope.dict[dictName] = res.attribute;
                            if(dictName == "visit_way"){
                                //增加默认值
                                $scope.visit.visitWay = "1";
                            }
                            if(dictName == "failure_reason"){
                                if($scope.visit.reason){
                                    var _reason = [];
                                    angular.forEach($scope.dict[dictName],function (value,key) {
                                        var _r = $scope.visit.reason[key];
                                        if(_r){
                                            _reason.push(value+'采购情况：'+_r);
                                        }
                                    });
                                    $scope.reason['text'] = _reason.join('，');

                                    angular.forEach($scope.visit.reason,function (value,key) {
                                        $scope.reason['value'][key] = value;
                                    });
                                }else{
                                    $scope.visit.reason = {};
                                }
                            }
                        }else{

                        }
                    })
                    .error(function(error){

                    })
                    .finally(function(){

                    });
            },findContacts = function(){
                HotelService.getContacts({
                    hotelId:$rootScope.EDIT_HOTEL.id,
                    pageNum:1,
                    pageSize:100
                })
                    .success(function(res){
                        var nullTip = '请先给酒店添加联系人';
                        if(res.success){
                            if(!res.attribute || res.attribute.rows.length<=0){
                                $cordovaToast.showShortBottom(nullTip);
                            }
                           formatContact(res.attribute.rows);
                        }else{
                            $cordovaToast.showShortBottom(nullTip);
                        }
                    })
                    .error(function(error){

                    })
                    .finally(function(){

                    });
            };
        $scope.visit = $rootScope.EDIT_DATE && $rootScope.EDIT_DATE[type] ? format($rootScope.EDIT_DATE[type]) : format({});

        $scope.dict = {
            'visit_type':{}, //拜访方式
            'visit_way':{}, //拜访类型
            'sample_grant':{}, //样品发放
            // 'purchase_intention':{}, //采购意向
            'unvisit_reason':{}, //未采购原因,
            'hotel_contacts':{}, //酒店联系人,
            'failure_reason':{}, //失败原因
            // 'T_F': {}
        };
        $scope.reason = {
            value:{},//
            text:'' //用于也没展示
        }; //分销为采购原因对象（备份）
        $scope.form = {
            modal:"",
            title:'采购商品情况说明',
            type:'MultiSelect',
            dict:[],
            otherValue:'',
            onOk:function(keys,values){
                var _this = this;
                $scope.visit.unvisitReason = keys.join(',');
                $scope.visit.unvisitReasonName = values.join('、');
                if($scope.visit.unvisitReasonName){
                    $scope.visit.unvisitReasonName += '、';
                }
                if(_this.otherValue){
                    $scope.visit.unvisitReasonName += _this.otherValue;
                }
                $scope.visit.other = _this.otherValue;
            }

        };
        $ionicModal.fromTemplateUrl('templates/modal/form-modal.html', {
            scope: $scope,
            animation: 'slide-in-right',
            hardwareBackButtonClose: true
        }).then(function (modal) {
            $scope.form.modal = modal;
        });

        //增加供应链拜访记录失败原因 2016-03-18 start


        //未采购编辑原因 model start
        $ionicModal.fromTemplateUrl('templates/modal/hotel-visit-reason-edit-modal.html', {
            scope: $scope,
            animation: 'slide-in-right',
            hardwareBackButtonClose: true
        }).then(function (modal) {
            $scope.form.visitReasonEditModal = modal;
        });

        $scope.showVisitReasonEditModalForm = function(key,value){
            $scope.reason['edit'] = {
                id:key,
                value:value
            };
            $scope.form.visitReasonEditModal.show();
        }
        $scope.onVisitReasonEditCancel = function(){
            $scope.form.visitReasonEditModal.hide();
        }

        $scope.onVisitReasonEditSave = function(){
            $scope.form.visitReasonEditModal.hide();
        }
        //未采购编辑原因 model end

        //未采购原因 model start
        $ionicModal.fromTemplateUrl('templates/modal/hotel-visit-reason-modal.html', {
            scope: $scope,
            animation: 'slide-in-right',
            hardwareBackButtonClose: true
        }).then(function (modal) {
            $scope.form.visitReasonModal = modal;
        });
        $scope.showVisitReasonModalForm = function(){
            $scope.form.visitReasonModal.show();
        };

        $scope.onVisitReasonCancel = function(){
            if($scope.visit.reason && Object.keys($scope.visit.reason).length>0 ){
                angular.forEach($scope.visit.reason,function (value,key) {
                    $scope.reason['value'][key] = value;
                });
            }else{
                $scope.reason = {};
            }
            $scope.form.visitReasonModal.hide();
        };
        //保存失败原因 -
        $scope.onVisitReasonSave = function(){
            if($scope.reason.value){
                var _reason = [],
                    _isError= false;
                angular.forEach($scope.dict['failure_reason'],function (value,key) {
                    if(!_isError){
                        var _r = $scope.reason.value[key];
                        if(_r){
                            _reason.push(value+'采购情况：'+_r);
                        }else{
                            var _msg = '请输入'+value+'采购情况';
                            _isError = true;
                            console.log(_msg);
                            $cordovaToast.showShortBottom(_msg);
                        }

                    }
                });
                if(_isError){
                    return;
                }
                $scope.reason['text'] = _reason.join('，');

                angular.forEach($scope.reason.value,function (value,key) {
                    $scope.visit.reason[key] = value;
                });
            }
            $scope.form.visitReasonModal.hide();
        }
        $ionicModal.fromTemplateUrl('templates/modal/hotel-visit-desc-modal.html', {
            scope: $scope,
            animation: 'slide-in-right',
            hardwareBackButtonClose: true
        }).then(function (modal) {
            $scope.form.visitDescEditModal = modal;
        });

        $scope.showVisitDescEditModalForm = function(){
            $scope.form.visitDescEditModal.show();
        }
        $scope.onVisitDescEditSave = function(){
            $scope.form.visitDescEditModal.hide();
        }
        //拜访情况 end

        $scope.showForm = function(){
            if($scope.form.dict.length<=0){
                angular.forEach($scope.dict['unvisit_reason'],function(value,key){
                    $scope.form.dict.push({
                        id:key,
                        name:value
                    });
                });
            }
            $scope.form.modal.show();
        };

        $scope.onVisitTypeChange = function (visitType) {
            if(visitType=='11'){ <!--供应链业务-->
                $scope.visit.purchaseIntention = 'T';
            }else if(visitType=='3'){ <!--分销业务-->
                $scope.visit.isSign = 'T';
            }
        };
        var saving = false;
        $scope.doSave = function(){
            if (saving) {
                return;
            }
            saving = true;
            var saveKeys = [{
                key:'visitWay',
                nullTip:'请选择拜访方式'
            },{
                key:'hotelContacts',
                nullTip:'请选择联系人'
            },{
                key:'visitDate',
                nullTip:'请选择拜访日期'
            },{
                key:'visitType',
                nullTip:'请选择拜访类型'
            }],key_visitDesc = {
                    key:'visitDesc',
                    nullTip:'请输入拜访情况'
            },saveValues = {
                id:$scope.visit.id,
                visitHotelId:$scope.visit.visitHotelId
            };
            if($scope.visit.visitType=='11'){ <!--供应链业务-->
                saveKeys.push({
                    key:'sampleGrant',
                    nullTip:'请选择样品发放'
                });
                saveKeys.push({
                    key:'purchaseIntention',
                    nullTip:'请选择采购意向'
                });
                saveKeys.push({
                    key:'reason',
                    nullTip:'请选择商品采购说明'
                });
                saveValues['visitDesc'] = $scope.visit['visitDesc'];
            }else if($scope.visit.visitType=='3'){ <!--分销业务-->
                saveKeys.push({
                    key:'isSign',
                    nullTip:'是否签约'
                });
                saveKeys.push(key_visitDesc);
            }else{
                saveKeys.push(key_visitDesc);
            }
            for(var i=0;i<saveKeys.length;i++){
                var item = saveKeys[i],
                    value = $scope.visit[item.key];
                if(!value || (item.key=='reason' && _.isEmpty(value)) ){
                    console.log(item.nullTip);
                    saving = false;
                    $cordovaToast.showShortBottom(item.nullTip);
                    return;
                }else{
                    saveValues[item.key] = $scope.visit[item.key];
                }
            }
            VisitService.insert(formatSave(saveValues))
                .success(function(res){
                    saving = false;
                    if(res.success){
                        $rootScope.$broadcast('EDIT_COMPLETE',{
                            'HotelVisitEdit':saveValues
                        });
                        $scope.$ionicGoBack();
                    }else{
                        $cordovaToast.showShortBottom('错误信息:' + res.errorMsg);
                    }
                })
                .error(function(){

                })
                .finally(function(){
                    $ionicLoading.hide();
                    saving = false;
                });
        };

        init();
    }])
.controller('HotelRankEditCtrl', ['$scope','$rootScope', '$state','RankService','$cordovaToast','$ionicLoading',
    function($scope,$rootScope, $state,RankService,$cordovaToast,$ionicLoading) {
        var type = 'HotelRankEdit',
            format = function(date){
                date.createTime = (new Date()).getTime();
                date.hotelName = $rootScope.EDIT_HOTEL.hotelName;
                date.hotelId = $rootScope.EDIT_HOTEL.id;
                return date;
            };
        $scope.rank = $rootScope.EDIT_DATE && $rootScope.EDIT_DATE[type] ? $rootScope.EDIT_DATE[type] : format({});
        $scope.rankDict = {
            'A':'A级',
            'B':'B级',
            'C':'C级'
        };
        var saving = false;
        $scope.doSave = function(){
            if (saving) {
                return;
            }
            saving = true;
            var saveKeys = [{
                key:'rank',
                nullTip:'请选择评级级别'
            },{
                key:'remark',
                nullTip:'请输入评级备注'
            }];
            for(var i=0;i<saveKeys.length;i++){
                var item = saveKeys[i];
                if(!$scope.rank[item.key]){
                    saving = false;
                    $cordovaToast.showShortBottom(item.nullTip);
                    return;
                }
            }
            $ionicLoading.show({
                template: '保存中...'
            });
            RankService.insert($scope.rank)
                .success(function(res){
                    saving = false;
                    if(res.success){
                        $rootScope.$broadcast('EDIT_COMPLETE',{
                            'HotelRankEdit':$scope.rank
                        });
                        $scope.$ionicGoBack();
                    }else{
                        $cordovaToast.showShortBottom('保存失败');
                    }
                })
                .error(function(){

                })
                .finally(function(){
                    saving = false;
                    $ionicLoading.hide();
                });
        };
    }])
.controller('HotelContactEditCtrl', ['$scope','$rootScope', '$state','ContactService','$cordovaToast','$ionicLoading',
    function($scope,$rootScope, $state,ContactService,$cordovaToast,$ionicLoading) {

    var type = 'HotelContactEdit',
        format = function(date){
            date.hotelId = $rootScope.EDIT_HOTEL.id;
            return date;
        };
    if ($rootScope.EDIT_DATE && $rootScope.EDIT_DATE[type]) {
        $scope.saveType = "修改";
        format($rootScope.EDIT_DATE[type]);
    } else {
        $scope.saveType = "添加";
    }
    $scope.contact = $rootScope.EDIT_DATE && $rootScope.EDIT_DATE[type] ? $rootScope.EDIT_DATE[type] : format({});
    $scope.contactDict = {
        '1':'老板',
        '2':'前台',
        '3':'经理',
        '4':'其他'
    };
    var saving = false;
    $scope.doSave = function(){
        if (saving) {
            return;
        }
        saving = true;
        var saveKeys = [{
            key:'name',
            nullTip:'请输入联系人姓名'
        },{
            key:'phone',
            nullTip:'请输入联系电话'
        },{
            key:'roleId',
            nullTip:'请选择联系人身份'
        }/*,{
            key:'remark',
            nullTip:'请输入备注'
        }*/];
        for(var i=0;i<saveKeys.length;i++){
            var item = saveKeys[i];
            if(!$scope.contact[item.key]){
                saving = false;
                $cordovaToast.showShortBottom(item.nullTip);
                return;
            }
        }
        $ionicLoading.show({
            template: '保存中...',
            animation: 'fade-in',
            showBackdrop: true,
            duration: 10000,
            showDelay: 0
        });
        if ($rootScope.EDIT_DATE && $rootScope.EDIT_DATE[type]) {
            ContactService.update($scope.contact).success(function(res) {
                saving = false;
                if(res.success){
                    $rootScope.$broadcast('EDIT_COMPLETE',{
                        'HotelContactEdit':$scope.contact
                    });
                    $scope.$ionicGoBack();
                }else{
                    $cordovaToast.showShortBottom('错误信息:' + res.errorMsg);
                }
            })
            .error(function(){

            })
            .finally(function(){
                saving = false;
                $ionicLoading.hide();
            });
        } else {
            ContactService.insert($scope.contact)
                .success(function(res){
                    saving = false;
                    if(res.success){
                        $rootScope.$broadcast('EDIT_COMPLETE',{
                            'HotelContactEdit':$scope.contact
                        });
                        $scope.$ionicGoBack();
                    }else{
                        $cordovaToast.showShortBottom('错误信息:' + res.errorMsg);
                    }
                })
                .error(function(){

                })
                .finally(function(){
                    saving = false;
                    $ionicLoading.hide();
                });
        }
    };

    // 销毁联系人信息
    $scope.$on('$destroy', function() {
        delete $rootScope.EDIT_DATE[type];
    });
}])

.service('LocationService',['CrmHttp','$rootScope',function(CrmHttp,$rootScope){
        var url = '/hotel/';
        return {
            /**
             * 获取省列表
             * @param params
             * @returns {*}
             */
            provinces: function () {
                var act = 'provinces',
                    params = {};
                return CrmHttp.post(url + act, params);
            },
            /**
             * 获取市列表
             * @param params
             * @returns {*}
             */
            cities: function (proId) {
                var act = 'cities',
                    params = {};
                params['proId'] = proId;
                return CrmHttp.post(url + act, params);
            },
            /**
             * 获取区列表
             * @param params
             * @returns {*}
             */
            districts: function (cityId) {
                var act = 'districts',
                    params = {};
                params['cityId'] = cityId;
                return CrmHttp.post(url + act, params);
            },
            /**
             * 保存位置信息
             * @param params
             * @returns {*}
             */
            setProvAndCityAndArea:function(params){
                var act = 'setProvAndCityAndArea';
                params['hotelId'] = $rootScope.EDIT_HOTEL.id;
                return CrmHttp.post('/crm/crm-hotel-public/' + act, params);
            },
            /**
             * 获取供应链拜访记录失败原因list
             * @param params
             * @returns {*}
             */
            selectVisitReasonList:function(){
                var act = 'findValueLabel';
                params['code'] = 'failure_reason';
                return CrmHttp.post('/crm/crm-visit-record/' + act, params);
            }

        };
    }]);